package com.yiyahui.project.erp.controller;

import java.util.List;

import com.yiyahui.project.erp.domain.YiyaMarketReservation;
import com.yiyahui.project.erp.service.IYiyaIDService;
import com.yiyahui.project.erp.service.IYiyaMarketReservationService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import com.yiyahui.framework.aspectj.lang.annotation.Log;
import com.yiyahui.framework.aspectj.lang.enums.BusinessType;
import com.yiyahui.project.erp.domain.YiyaClinicPerson;
import com.yiyahui.project.erp.service.IYiyaClinicPersonService;
import com.yiyahui.project.erp.service.IYiyaOperationLogService;
import com.yiyahui.framework.web.controller.BaseController;
import com.yiyahui.framework.web.domain.AjaxResult;
import com.yiyahui.common.utils.StringUtils;
import com.yiyahui.common.utils.poi.ExcelUtil;
import com.yiyahui.framework.web.page.TableDataInfo;

import static org.assertj.core.util.DateUtil.now;

/**
 * 到店患者信息Controller
 * 
 * @author yiyahui
 * @date 2020-05-08
 */
@Api("到店患者信息")
@RestController
@RequestMapping("/erp/person")
public class YiyaClinicPersonController extends BaseController {
    @Autowired
    private IYiyaClinicPersonService yiyaClinicPersonService;

    @Autowired
    private IYiyaOperationLogService yiyaOperationLogService;

    @Autowired
    private IYiyaIDService yiyaIDService;

    @Autowired
    private IYiyaMarketReservationService yiyaMarketReservationService;

    /**
     * 查询到店患者信息列表
     */
    @ApiOperation("查询到店患者信息列表")
    @PreAuthorize("@ss.hasPermi('erp:person:list')")
    @GetMapping("/list")
    public TableDataInfo list(YiyaClinicPerson yiyaClinicPerson) {
        startPage();
        List<YiyaClinicPerson> list = yiyaClinicPersonService.selectYiyaClinicPersonList(yiyaClinicPerson);
        return getDataTable(list);
    }

    /**
     * 导出到店患者信息列表
     */
    @ApiOperation("导出到店患者信息列表")
    @PreAuthorize("@ss.hasPermi('erp:person:export')")
    @Log(title = "到店患者信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(YiyaClinicPerson yiyaClinicPerson) {
        List<YiyaClinicPerson> list = yiyaClinicPersonService.selectYiyaClinicPersonList(yiyaClinicPerson);
        ExcelUtil<YiyaClinicPerson> util = new ExcelUtil<YiyaClinicPerson>(YiyaClinicPerson.class);
        return util.exportExcel(list, "person");
    }

    /**
     * 获取到店患者信息详细信息
     */
    @ApiOperation("获取到店患者信息详细信息")
    @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "Long", paramType = "path")
    @PreAuthorize("@ss.hasPermi('erp:person:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        yiyaOperationLogService.insertDailyBrowserLog(1, id);
        return AjaxResult.success(yiyaClinicPersonService.selectYiyaClinicPersonById(id));
    }

    /**
     * 新增到店患者信息
     */
    @ApiOperation("新增到店患者信息")
    @ApiImplicitParam(name = "yiyaClinicPerson", value = "${tableComment}", dataType = "YiyaClinicPerson")
    @PreAuthorize("@ss.hasPermi('erp:person:add')")
    @Log(title = "到店患者信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YiyaClinicPerson yiyaClinicPerson) {
        String caseNum = null;
        if (yiyaClinicPerson.getIsTemporary() != null && yiyaClinicPerson.getIsTemporary().equals(1)
                && !"".equals(yiyaClinicPerson.getArriveClinic())) {
            if (StringUtils.isNull(yiyaClinicPerson.getArriveClinic()))
                caseNum = yiyaIDService.createYiyaID(IYiyaIDService.IDType_BINGLIHAO, yiyaClinicPerson.getName());
            else
                caseNum = yiyaIDService.createYiyaID(IYiyaIDService.IDType_BINGLIHAO,
                        yiyaClinicPerson.getArriveClinic());
            yiyaClinicPerson.setFirstOnClinicTime(now());
            yiyaClinicPerson.setCaseNumber(caseNum);
        }
        if (yiyaClinicPerson.getIsTemporary() != null && yiyaClinicPerson.getIsTemporary().equals(0)
                && !"".equals(yiyaClinicPerson.getArriveClinic())) {
            if (StringUtils.isNull(yiyaClinicPerson.getArriveClinic()))
                caseNum = yiyaIDService.createYiyaID(IYiyaIDService.IDType_LINSHIHAO, yiyaClinicPerson.getName());
            else
                caseNum = yiyaIDService.createYiyaID(IYiyaIDService.IDType_LINSHIHAO,
                        yiyaClinicPerson.getArriveClinic());

            yiyaClinicPerson.setCaseNumber(caseNum);
        }
        createMarkReservationRequest(yiyaClinicPerson, caseNum);
        int count = yiyaClinicPersonService.insertYiyaClinicPerson(yiyaClinicPerson);
        if (count > 0) {
            return AjaxResult.success("操作成功", yiyaClinicPerson.getId());
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 修改到店患者信息
     */
    @ApiOperation("修改到店患者信息")
    @ApiImplicitParam(name = "yiyaClinicPerson", value = "${tableComment}", dataType = "YiyaClinicPerson")
    @PreAuthorize("@ss.hasPermi('erp:person:edit')")
    @Log(title = "到店患者信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YiyaClinicPerson yiyaClinicPerson) {
        String caseNum = null;
        YiyaClinicPerson oldPerson = yiyaClinicPersonService.selectYiyaClinicPersonById(yiyaClinicPerson.getId());

        if (oldPerson.getIsTemporary().equals(0)) {
            // 如果原来是临时，当前转为正式
            // 修改到店时间，设置正式用户病历号
            if (yiyaClinicPerson.getIsTemporary() != null && yiyaClinicPerson.getIsTemporary().equals(1)
                    && !"".equals(yiyaClinicPerson.getArriveClinic())) {
                if (StringUtils.isNull(yiyaClinicPerson.getArriveClinic()))
                    caseNum = yiyaIDService.createYiyaID(IYiyaIDService.IDType_BINGLIHAO, yiyaClinicPerson.getName());
                else
                    caseNum = yiyaIDService.createYiyaID(IYiyaIDService.IDType_BINGLIHAO,
                            yiyaClinicPerson.getArriveClinic());
                yiyaClinicPerson.setFirstOnClinicTime(now());
                yiyaClinicPerson.setCaseNumber(caseNum);
            }
        } else {
            yiyaClinicPerson.setArriveClinic(null);
        }

        if (yiyaClinicPerson.getIsTemporary() != null && yiyaClinicPerson.getIsTemporary().equals(0)
                && !"".equals(yiyaClinicPerson.getArriveClinic())) {
            if (StringUtils.isNull(yiyaClinicPerson.getArriveClinic()))
                caseNum = yiyaIDService.createYiyaID(IYiyaIDService.IDType_LINSHIHAO, yiyaClinicPerson.getName());
            else
                caseNum = yiyaIDService.createYiyaID(IYiyaIDService.IDType_LINSHIHAO,
                        yiyaClinicPerson.getArriveClinic());
            yiyaClinicPerson.setCaseNumber(caseNum);
        }
        createMarkReservationRequest(yiyaClinicPerson, caseNum);
        if (yiyaClinicPerson.getPhoneNumber() != null)
            if (yiyaClinicPerson.getPhoneNumber().contains("***"))
                yiyaClinicPerson.setPhoneNumber("");
        if (yiyaClinicPerson.getPhoneNumber2() != null)
            if (yiyaClinicPerson.getPhoneNumber2().contains("***"))
                yiyaClinicPerson.setPhoneNumber2("");
        return toAjax(yiyaClinicPersonService.updateYiyaClinicPerson(yiyaClinicPerson));
    }

    private void createMarkReservationRequest(@RequestBody YiyaClinicPerson yiyaClinicPerson, String caseNum) {
        if (yiyaClinicPerson.getMarketReservationId() != null && yiyaClinicPerson.getMarketReservationId() > 0) {
            YiyaMarketReservation yiyaMarketReservationResponse = yiyaMarketReservationService
                    .selectYiyaMarketReservationById(yiyaClinicPerson.getMarketReservationId());
            if (!"已到店".equals(yiyaMarketReservationResponse.getReachState())) {
                if (yiyaClinicPerson.getIsTemporary() == null || yiyaClinicPerson.getIsTemporary().equals(1)) {
                    yiyaMarketReservationResponse
                            .setAffiliationPerson(yiyaMarketReservationResponse.getFollowPerson() != null
                                    ? yiyaMarketReservationResponse.getFollowPerson()
                                    : yiyaMarketReservationResponse.getFilingPerson());
                    yiyaMarketReservationResponse
                            .setFollowPerson(yiyaMarketReservationResponse.getFollowPerson() != null
                                    ? yiyaMarketReservationResponse.getFollowPerson()
                                    : yiyaMarketReservationResponse.getFilingPerson());
                    yiyaMarketReservationResponse.setOnClinicTime(now());
                    yiyaMarketReservationResponse.setFirstTc(yiyaClinicPerson.getFirstTc());
                    yiyaMarketReservationResponse.setReachState("已到店"); // 客户状态
                }
                //0923-病历号只要被生成，则会同步到市场表
                if (StringUtils.isNotNull(caseNum))
                    yiyaMarketReservationResponse.setCaseNumber(caseNum);
                yiyaMarketReservationService.updateYiyaMarketReservation(yiyaMarketReservationResponse);
            }
            yiyaClinicPerson.setPhoneNumber(yiyaMarketReservationResponse.getPhoneNumber());
            yiyaClinicPerson.setPhoneOwnership(yiyaMarketReservationResponse.getPhoneOwnership());
        }
    }

    /**
     * 删除到店患者信息
     */
    @ApiOperation("删除到店患者信息")
    @ApiImplicitParam(name = "ids", value = "主键id数组", required = true, dataType = "Long[]", paramType = "path")
    @PreAuthorize("@ss.hasPermi('erp:person:remove')")
    @Log(title = "到店患者信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(yiyaClinicPersonService.deleteYiyaClinicPersonByIds(ids));
    }
}
